﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Pur;
using ESOL.Business.Prod;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Proj
{
    public partial class frmMaintainProductPlanOrderPurchase : BaseForm.frmBaseDialogyMaintainForm
    {
        #region vars
        public PurApplicationEntity SelectedPurApplication { get; set; }
        private List<PurApplicationItemEntity> DeleteList = new List<PurApplicationItemEntity>();

        public List<ProdPlanOrderItemEntity> mListProdPlanOrderItems { set; get; }
        public ProdPlanOrderEntity mSelectedPlanOrder { set; get; }
        #endregion

        #region ctors
        public frmMaintainProductPlanOrderPurchase()
        {
            InitializeComponent();
            if (SelectedPurApplication == null)
            {
                SelectedPurApplication = new PurApplicationEntity();
                SelectedPurApplication.ApplicationId = Guid.NewGuid().ToString();
                SelectedPurApplication.IsProductPurchase = 0;
            }
        }
        #endregion

        #region functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByEnum(cmbIsProductPurchase, typeof(PurchaseCategory), typeof(int), false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPurchaseType, "PURTYPE", true);
            DataTable dt = MstCommonItemBs.GetMstCommonItemDtByType("UNIT");
            repositoryItemGridLookUpEdit1.DataSource = dt;
            repositoryItemGridLookUpEdit1.DisplayMember = "ITEM_NAME";
            repositoryItemGridLookUpEdit1.ValueMember = "ITEM_CODE";
        }

        private void BindGridMain()
        {
            DataTable dt = PurApplicationItemBs.GetDataSetByApplicationID("QueryNull").Tables[0];
            gvDetail.DataSource = dt;
            if (mListProdPlanOrderItems == null || mListProdPlanOrderItems.Count <= 0)
                return;
            foreach (ProdPlanOrderItemEntity m in mListProdPlanOrderItems)
            {
                DataRow dr = dt.NewRow();
                dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["APPLICATION_ID"] = SelectedPurApplication.ApplicationId;
                dr["PRODUCT_ID"] = m.ProductId;
                dr["QTY"] = m.Qty;
                MstProductEntity mMstProduct = MstProductBs.GetMstProductTypeByID(m.ProductId);
                if (mMstProduct != null)
                {
                    dr["PRODUCT_NAME"] = mMstProduct.ProductName;
                    dr["PRODUCT_CODE"] = mMstProduct.ProductCode;
                    dr["PRODUCT_SPEC_IN"] = mMstProduct.ProductSpecIn;
                    dr["MATERIAL"] = mMstProduct.Material;
                    dr["UNIT"] = mMstProduct.Unit;
                    dr["DESCRIPTION"] = mMstProduct.Description;
                }
                dr["PLAN_ORDER_ITEM_ID"] = m.PlanOrderItemId;
                dt.Rows.Add(dr);
            }

        }

        private void SetFields()
        {
            if (SelectedPurApplication == null)
            {
                return;
            }
            txtApplicationCode.Text = SelectedPurApplication.ApplicationCode;
            if (string.IsNullOrEmpty(txtApplicationCode.Text))
            {
                txtApplicationCode.Text = "自动生成";
            }
            if (ThisActionType == ActionType.New)
            {
                dtpApplicationDate.EditValue = DateTime.Now;
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtApplicationPerson.Tag = person;
                    txtApplicationPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
            }
            else
            {
                dtpApplicationDate.EditValue = SelectedPurApplication.ApplicationDate;
                dtpDeliveryRequiredDate.EditValue = SelectedPurApplication.DeliveryRequiredDate;
                if (string.IsNullOrEmpty(SelectedPurApplication.ApplicationPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedPurApplication.ApplicationPerson);
                    if (person != null)
                    {
                        txtApplicationPerson.Tag = person;
                        txtApplicationPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            cmbIsProductPurchase.SetSelectedValue(SelectedPurApplication.IsProductPurchase);
            cmbPurchaseType.SetSelectedValue("PURTYPE01");
            cmbStatus.SetSelectedValue(SelectedPurApplication.Status);
            txtRemark.Text = SelectedPurApplication.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, DateTime.Today, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, Common.CommonParameter.CurrentUser.PersonId);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedPurApplication.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedPurApplication.LastModifiedBy);
        }

        private void SetEntity()
        {
            if (mSelectedPlanOrder != null)
            {
                SelectedPurApplication.PlanOrderId = mSelectedPlanOrder.PlanOrderId;
            }
            if (dtpApplicationDate.EditValue!=null)
            {
                SelectedPurApplication.ApplicationDate = (DateTime)dtpApplicationDate.EditValue;
            }
            if (dtpDeliveryRequiredDate.EditValue != null)
            {
                SelectedPurApplication.DeliveryRequiredDate = (DateTime)dtpDeliveryRequiredDate.EditValue;
            }
            if (txtApplicationPerson.Tag != null && txtApplicationPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedPurApplication.ApplicationPerson = ((MstPersonEntity)txtApplicationPerson.Tag).PersonId;
            }
            if (cmbIsProductPurchase.SelectedValue != null && cmbIsProductPurchase.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurApplication.IsProductPurchase = CommonFunctions.ToInt32(cmbIsProductPurchase.SelectedValue);
            }
            if (cmbPurchaseType.SelectedValue != null && cmbPurchaseType.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurApplication.PurchaseType = cmbPurchaseType.SelectedValue.ToString().Trim();
            }
            SelectedPurApplication.Status = NormalStatus.STATUS01.ToString();
            SelectedPurApplication.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedPurApplication.CreatedDate = DateTime.Now;
                SelectedPurApplication.CreatedBy = CommonParameter.CurrentUser.UserId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedPurApplication.LastModifiedDate = DateTime.Now;
                SelectedPurApplication.LastModifiedBy = CommonParameter.CurrentUser.UserId;
            }
        }

        private bool CheckData()
        {
            if (dtpApplicationDate.EditValue == null)
            {
                MessageBox.Show("申请日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbIsProductPurchase.SelectedValue == null || cmbIsProductPurchase.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("采购方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbPurchaseType.SelectedValue == null || cmbPurchaseType.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("采购类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtApplicationPerson.Text))
            {
                MessageBox.Show("申请人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("采购申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = PurApplicationBs.SaveApplication(true, SelectedPurApplication, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                //else if (ThisActionType == ActionType.Modify)
                //{
                //    SetEntity();
                //    List<PurProductPurchaseEntity> listMap = GetProdPlanOrder();
                //    DataTable dt = (DataTable)gvDetail.DataSource;
                //    bool isSuccessful = PurApplicationBs.SaveApplication(false, SelectedPurApplication, listMap, dt, DeleteList);
                //    if (!isSuccessful)
                //    {
                //        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //        return false;
                //    }
                //}
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedPurApplication.ApprovedDate = DateTime.Now;
                    SelectedPurApplication.ApprovedBy = CommonParameter.CurrentUser.UserId;
                    bool isSuccessful = PurApplicationBs.UpdatePurApplication(SelectedPurApplication);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            BindGridMain();
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                MessageBox.Show("外购申请成功！","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtApplicationPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtApplicationPerson.Text = frm.SelectedPerson.NameCn;
                txtApplicationPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtApplicationPerson.Text = "";
                txtApplicationPerson.Tag = null;
            }
        }

        private void dtpDeliveryRequiredDate_EditValueChanged(object sender, EventArgs e)
        {
            if (dtpDeliveryRequiredDate.EditValue == null)
                return;
            DataTable dt = (DataTable)gvDetail.DataSource;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    dr["DELIVERY_REQUIRED_DATE"] = (DateTime)dtpDeliveryRequiredDate.EditValue;
                }
            }
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            DataTable dt = gvDetail.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView1.GetFocusedDataRow();
            DataTable dt = gvDetail.DataSource as DataTable;
            dt.Rows.Remove(dr);
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainMBOMQuery frm = new frmMaintainMBOMQuery(mSelectedPlanOrder);
            if (frm.ShowDialog() == DialogResult.OK&&frm.SelectedProductBomMaster!=null)
            {
                MstProductEntity mProduct=MstProductBs.GetMstProductTypeByID(frm.SelectedProductBomMaster.ProductId);
                DataRow dr=gridView1.GetDataRow(gridView1.FocusedRowHandle);
                dr["PRODUCT_NAME"] = mProduct.ProductName;
                dr["PRODUCT_CODE"]=mProduct.ProductCode;
                dr["DESCRIPTION"] = mProduct.Description;
                dr["PRODUCT_SPEC_IN"] = mProduct.ProductSpecIn;
                dr["MATERIAL"] = mProduct.Material;
                dr["UNIT"] = mProduct.Unit;
                dr["QTY"] = mSelectedPlanOrder.Qty * frm.SelectedProductBomMaster.UnitDose;
                dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["APPLICATION_ID"] = SelectedPurApplication.ApplicationId;
                dr["PRODUCT_ID"] = mProduct.ProductId;
            }
        }

        #endregion




    }
}
